package com.yys.apm.service;

import com.yys.apm.boot.ApmAgentManager;
import com.yys.apm.config.ApmConfig;
import com.yys.apm.logger.ILogger;
import com.yys.apm.logger.LoggerManager;
import com.yys.apm.model.HeartbeatInfo;
import com.yys.apm.boot.spi.ServiceSPI;
import com.yys.apm.utils.ApmAgentUtil;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 心跳上报服务
 *
 * @author Yingsheng Ye
 * @date 2021-03-20 22:31
 */
@ServiceSPI
public class HeartbeatReportService implements ApmService {

    private static final ILogger logger = LoggerManager.getLogger(HeartbeatReportService.class);

    private ScheduledExecutorService taskExecutor;

    private static String CLIENT_URL;

    private static String SECRET_KEY;

    @Override
    public void prepare() {
        ApmAgentManager agentManager = ApmAgentManager.getInstance();
        CLIENT_URL = agentManager.properties.getProperty(ApmConfig.PUSH_CLIENT_URL);
        SECRET_KEY = agentManager.properties.getProperty(ApmConfig.PUSH_SECRET_KEY);
        this.taskExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r, "heartbeat-task");
            thread.setDaemon(true);
            return thread;
        });
    }

    @Override
    public void startup() {
        this.taskExecutor.scheduleWithFixedDelay(() -> {
            HeartbeatInfo heartbeatInfo = new HeartbeatInfo();
            heartbeatInfo.setAppId(ApmAgentManager.getInstance().properties.getProperty(ApmConfig.APP_ID));
            heartbeatInfo.setMsg("心跳");
            String data = ApmAgentUtil.objectToJson(heartbeatInfo);
            logger.info("心跳包上报:%s", data);
            ApmAgentUtil.sendHttpRequest(CLIENT_URL, ApmAgentUtil.buildRequestPkg(data, "heartbeatService", SECRET_KEY));
        }, 60, 60, TimeUnit.SECONDS);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void shutdown() {
        this.taskExecutor.shutdown();
    }
}
